package com.shop.shoppingmall.service.impl;

import com.shop.shoppingmall.dao.ShRechargeDao;
import com.shop.shoppingmall.dao.ShUserDao;
import com.shop.shoppingmall.entity.ShRecharge;
import com.shop.shoppingmall.entity.ShUser;
import com.shop.shoppingmall.service.ShRechargeService;
import com.shop.shoppingmall.util.CommonConstant;
import com.shop.shoppingmall.util.JwtUtil;
import com.shop.shoppingmall.util.UUIDGenerator;
import com.shop.shoppingmall.util.api.vo.Result;
import com.shop.shoppingmall.util.oConvertUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * (ShRecharge)表服务实现类
 *
 * @author makejava
 * @since 2020-11-20 09:54:10
 */
@Service("shRechargeService")
public class ShRechargeServiceImpl implements ShRechargeService {
    @Resource
    private ShRechargeDao shRechargeDao;
    @Resource
    private ShUserDao shUserDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public ShRecharge queryById(String id) {
        return this.shRechargeDao.queryById(id);
    }

    /**
     * 新增数据
     *
     * @param shRecharge 实例对象
     * @return 实例对象
     */
    @Override
    public ShRecharge insert(ShRecharge shRecharge) {
        this.shRechargeDao.insert(shRecharge);
        return shRecharge;
    }

    /**
     * 修改数据
     *
     * @param shRecharge 实例对象
     * @return 实例对象
     */
    @Override
    public ShRecharge update(ShRecharge shRecharge) {
        this.shRechargeDao.update(shRecharge);
        return this.queryById(shRecharge.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String id) {
        return this.shRechargeDao.deleteById(id) > 0;
    }

    /**
     * 开通会员下单
     * @param
     * @param
     * @return
     */
    @Override
    public Result selectRechargeByUserId(HttpServletRequest request) {
        String nameByToken = JwtUtil.getUserNameByToken(request);
        ShUser shUser = shUserDao.selectLoginName(nameByToken);
        if(shUser == null){
            return Result.error(CommonConstant.SC_OK_201,"您还未注册或者登录，请先注册或登录");
        }
        String userId = shUser.getId();
        ShRecharge shRecharges = new ShRecharge();
        shRecharges.setId(UUIDGenerator.generate());
        shRecharges.setOrderName("开通会员");
        shRecharges.setOrderNumber(oConvertUtils.randomGen(16));
        shRecharges.setUserId(userId);
        shRecharges.setOrderPrice(new BigDecimal(168));
        shRecharges.setOrderStatus("1");

        shRechargeDao.insert(shRecharges);
        Map<String,Object> map = new HashMap<>();
        map.put("orderNumber",shRecharges.getOrderNumber());
        return Result.ok(map);
    }
}
